#/bin/bash
# /etc/xarxeta/control_actius.sh
# per afegir macs a la taula x_actius
# llegeix si hi ha nous registres a la taula x_alta; si és així, cerca la MAC
# cal afegir-ho al crontab!

# Importem valors de l'arxiu variables.xrx
user=`grep user_mysql /etc/xarxeta/variables.xrx`
user=${user:11}
pass=`grep pass_mysql /etc/xarxeta/variables.xrx`
pass=${pass:11}

clau=""
ip=""
dalta=""
dbaixa=""
mac=""
reinici=""

data_actual=""
data_actual=$(date +"%Y-%m-%d %H:%M:%S")

while  [ $(date +"%M") -le ${data_actual:14:2} ] && [ $(date +"%S") -le "55" ] 
do

count=$(echo "select count(*) from x_alta" | mysql -u $user -p$pass -D xarxeta | grep -v "count")
(( count-- ))
i=0

while [ $i -le $count ]
 do
  clau=$(echo "select clau from x_alta order by id_alta limit $i,1" | mysql -u $user -p$pass -D xarxeta | grep -v "clau")
  ip=$(echo "select ip from x_alta order by id_alta limit $i,1" | mysql -u $user -p$pass -D xarxeta | grep -v "ip")
  dalta=$(echo "select dAlta from x_alta order by id_alta limit $i,1" | mysql -u $user -p$pass -D xarxeta | grep -v "dAlta")
  dbaixa=$(echo "select dBaixa from x_alta order by id_alta limit $i,1" | mysql -u $user -p$pass -D xarxeta | grep -v "dBaixa")
  id=$(echo "select id_alta from x_alta order by id_alta limit $i,1" | mysql -u $user -p$pass -D xarxeta | grep -v "id_alta")

  if ! [[ -z $ip ]]
  then
   mac=`nmap $ip | grep 'MAC Address'`
   mac=${mac:13:17}
   if ! [[ -z $mac ]]
    then
     echo "INSERT INTO x_actius VALUES (NULL, '$clau', '$mac', '$dalta', '$dbaixa')" | mysql -u $user -p$pass -D xarxeta
     echo "delete from x_alta where id_alta=$id" | mysql -u $user -p$pass -D xarxeta
     (( count-- ))
     reinici="True"
    else
     (( i++ ))
   fi
   else
    (( i++ ))
  fi
done

 if [[ $reinici == "True" ]]
 then
  break
 fi
 sleep 2
done



if [[ $reinici == "True" ]]
then
 /etc/init.d/rules.sh
fi
